import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:zhaoxiaowu_app/components/view.dart';
import 'package:zhaoxiaowu_app/utils/utils.dart';
import 'package:zhaoxiaowu_app/viewmodels/register_viewmodel.dart';

class RegisterView extends StatefulWidget {
  @override
  _RegisterViewState createState() => _RegisterViewState();
}

class _RegisterViewState extends State<RegisterView> {
  late TextEditingController _account;
  late TextEditingController _phone;
  late TextEditingController _msgCode;
  late TextEditingController _password;
  late TextEditingController _name;

  @override
  void initState() {
    super.initState();
    _account = TextEditingController();
    _phone = TextEditingController();
    _msgCode = TextEditingController();
    _password = TextEditingController();
    _name = TextEditingController();

    if (context.read<RegisterViewModel>().countTime > 0) {
      _countDownTask();
    }
  }

  @override
  void dispose() {
    super.dispose();
    _account.dispose();
    _phone.dispose();
    _msgCode.dispose();
    _password.dispose();
    _name.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar("注册"),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent, // 触摸收起键盘
        onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(10),
            child: Form(
              child: Column(
                children: [
                  _getAccountWidget(),
                  _getPhoneWidget(),
                  _getMsgCodeWidget(),
                  _getPasswordWidget(),
                  _getNameWidget(),
                  _getBirthDayWidget(),
                  Container(
                    margin: EdgeInsets.fromLTRB(10, 30, 10, 10),
                    width: double.infinity,
                    height: 50,
                    child: ElevatedButton(
                      child: Text("注 册"),
                      onPressed: _register,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _getAccountWidget() {
    return TextFormField(
      controller: _account,
      decoration: InputDecoration(
        labelText: "注册账号",
        hintText: "请输入注册账号",
        hintStyle: TextStyle(fontSize: 14),
        prefixIcon: Icon(Icons.person),
      ),
      textInputAction: TextInputAction.next,
    );
  }

  Widget _getPhoneWidget() {
    return TextFormField(
      controller: _phone,
      decoration: InputDecoration(
        labelText: "手机号码",
        hintText: "请输入手机号码",
        hintStyle: TextStyle(fontSize: 14),
        prefixIcon: Icon(Icons.phone),
      ),
      textInputAction: TextInputAction.send,
      keyboardType: TextInputType.phone,
    );
  }

  Widget _getMsgCodeWidget() {
    return Stack(
      children: [
        TextFormField(
          controller: _msgCode,
          decoration: InputDecoration(
            labelText: "验证码",
            hintText: "请输入验证码",
            hintStyle: TextStyle(fontSize: 14),
            prefixIcon: Icon(Icons.message),
          ),
          textInputAction: TextInputAction.next,
          keyboardType: TextInputType.number,
        ),
        Positioned(
          top: 5,
          right: 10,
          child: ElevatedButton(
            child: Text(Provider.of<RegisterViewModel>(context).sendMsgCodeText),
            style: ElevatedButton.styleFrom(
              textStyle: TextStyle(fontSize: 14),
            ),
            onPressed: context.read<RegisterViewModel>().countTime > 0 ? null : _getMsgCode,
          ),
        ),
      ],
    );
  }

  Widget _getPasswordWidget() {
    return TextFormField(
      controller: _password,
      decoration: InputDecoration(
        labelText: "登录密码",
        hintText: "请输入登录密码",
        hintStyle: TextStyle(fontSize: 14),
        prefixIcon: Icon(Icons.lock),
      ),
      textInputAction: TextInputAction.next,
      obscureText: true,
    );
  }

  Widget _getNameWidget() {
    return Stack(
      children: [
        TextFormField(
          controller: _name,
          decoration: InputDecoration(
            labelText: "中文姓名",
            hintText: "请输入中文姓名",
            hintStyle: TextStyle(fontSize: 14),
            prefixIcon: Icon(Icons.account_box),
          ),
          keyboardType: TextInputType.text,
        ),
        Positioned(
          top: 5,
          right: 10,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Switch(
                value: Provider.of<RegisterViewModel>(context).isMale,
                onChanged: (v) => context.read<RegisterViewModel>().setGender(v),
              ),
              SizedBox(height: 8),
              Text(Provider.of<RegisterViewModel>(context).gender),
            ],
          ),
        ),
      ],
    );
  }

  Widget _getBirthDayWidget() {
    return Stack(
      children: [
        GestureDetector(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            height: 50,
            width: double.infinity,
            child: Row(
              children: [
                Text("出生日期"),
                SizedBox(width: 8),
                Text(Provider.of<RegisterViewModel>(context).birthDayText),
              ],
            ),
          ),
          onTap: _alertDateTime,
        ),
        Positioned(
          right: 10,
          child: Row(
            children: [
              Switch(
                value: Provider.of<RegisterViewModel>(context).isSolar,
                onChanged: ((v) => context.read<RegisterViewModel>().setSolar(v)),
              ),
              SizedBox(width: 8),
              Text(Provider.of<RegisterViewModel>(context).solarText),
            ],
          ),
        ),
      ],
    );
  }

  void _alertDateTime() {
    showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(1990),
      lastDate: DateTime.now(),
    ).then((value) {
      context.read<RegisterViewModel>().setBirthDay(value);
    }).catchError((e) {
      print(e);
    });
  }

  /// 获取短信验证码
  void _getMsgCode() {
    context.read<RegisterViewModel>().setCountTime(60);

    _countDownTask();
  }

  void _countDownTask() {
    Future.delayed(Duration(seconds: 1), () {
      if (mounted) {
        context.read<RegisterViewModel>().countDown();

        if (context.read<RegisterViewModel>().countTime > 0) {
          _countDownTask();
        }
      }
    });
  }

  void _register() {
    if (_account.text.trim().isEmpty) {
      ToastUtils.showToast("账号不能为空");
      return;
    } else if (_phone.text.trim().isEmpty) {
      ToastUtils.showToast("手机不能为空");
      return;
    } else if (_msgCode.text.trim().isEmpty) {
      ToastUtils.showToast("验证码不能为空");
      return;
    } else if (_password.text.trim().isEmpty) {
      ToastUtils.showToast("密码不能为空");
      return;
    } else if (_name.text.trim().isEmpty) {
      ToastUtils.showToast("姓名不能为空");
      return;
    } else if (context.read<RegisterViewModel>().birthDayText == "请选择日期") {
      ToastUtils.showToast("生日不能为空");
      return;
    }

    context.read<RegisterViewModel>().login(
          _account.text.trim(),
          _phone.text.trim(),
          _msgCode.text.trim(),
          _password.text.trim(),
          _name.text.trim(),
        );
  }
}
